/**
 * FrameAnimationController - 帧动画控制器
 *
 * 核心特性：
 * - 纯粹的帧索引管理，不关心具体渲染内容
 * - 支持播放/暂停/停止等完整控制
 * - 可选的平滑过渡（LayoutAnimation）
 * - 命令式控制（通过 ref）
 * - 灵活的时序模式（interval/raf）
 * - 完整的 TypeScript 类型支持
 *
 * 设计理念：
 * - 主组件只负责"时间"（帧索引管理）
 * - 子组件负责"空间"（视觉呈现）
 * - 通过 Render Props 模式解耦
 *
 * @example
 * ```tsx
 * const animRef = useRef<FrameAnimationControllerRef>(null);
 *
 * <FrameAnimationController
 *   ref={animRef}
 *   frameCount={3}
 *   frameDuration={200}
 *   loop={true}
 * >
 *   {(frameIndex) => (
 *     // 根据 frameIndex 渲染不同内容
 *     <YourCustomFrameView currentFrame={frameIndex} />
 *   )}
 * </FrameAnimationController>
 *
 * // 命令式控制
 * animRef.current?.play();
 * animRef.current?.pause();
 * ```
 */

import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef, useCallback } from 'react';
import { LayoutAnimation, Platform, UIManager } from 'react-native';
import type { FrameAnimationControllerProps, FrameAnimationControllerRef } from './types';

// Android 需要手动启用 LayoutAnimation
if (Platform.OS === 'android') {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}

/**
 * 帧动画控制器组件
 */
export const FrameAnimationController = forwardRef<FrameAnimationControllerRef, FrameAnimationControllerProps>(
  (
    {
      frameCount,
      frameDuration = 200,
      autoPlay = false,
      loop = true,
      initialFrame = 0,
      smoothTransition = false,
      transitionDuration,
      timingMode = 'interval',
      onFrameChange,
      onPlayEnd,
      onPlayStart,
      onPause,
      children,
    },
    ref,
  ) => {
    // ==================== 状态管理 ====================

    const [currentFrame, setCurrentFrame] = useState(initialFrame);
    const [isPlaying, setIsPlaying] = useState(autoPlay);
    const [duration, setDuration] = useState(frameDuration);
    const [shouldLoop, setShouldLoop] = useState(loop);

    // 定时器引用
    const timerRef = useRef<number | undefined>(undefined);
    const rafRef = useRef<number | undefined>(undefined);

    // 上一次播放状态，用于触发回调
    const wasPlayingRef = useRef(autoPlay);

    // RAF 模式的时间基准和帧索引（使用 ref 避免触发重渲染）
    const startTimeRef = useRef<number>(0);
    // const pausedTimeRef = useRef<number>(0); // 暂停时已经播放的累积时间
    const lastFrameIndexRef = useRef<number>(0);

    // ==================== 核心方法 ====================

    /**
     * 更新帧（带可选的 LayoutAnimation 支持）
     */
    const updateFrame = useCallback(
      (newFrame: number) => {
        if (smoothTransition) {
          LayoutAnimation.configureNext({
            duration: transitionDuration ?? duration * 1,
            update: {
              type: LayoutAnimation.Types.easeInEaseOut,
            },
          });
        }

        setCurrentFrame(newFrame);
        onFrameChange?.(newFrame);
      },
      [smoothTransition, transitionDuration, duration, onFrameChange],
    );

    /**
     * 清理所有定时器
     */
    const clearTimers = useCallback(() => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = undefined;
      }
      if (rafRef.current) {
        cancelAnimationFrame(rafRef.current);
        rafRef.current = undefined;
      }
    }, []);

    // ==================== 动画逻辑 ====================

    useEffect(() => {
      // 触发播放状态变化回调
      if (isPlaying && !wasPlayingRef.current) {
        onPlayStart?.();
      } else if (!isPlaying && wasPlayingRef.current) {
        onPause?.();
      }
      wasPlayingRef.current = isPlaying;

      if (!isPlaying) {
        clearTimers();
        return;
      }

      if (timingMode === 'interval') {
        // ========== 选项A: setInterval 模式 ==========
        // 优点：性能好，省电
        // 适用：大多数场景，特别是 frameDuration > 100ms

        timerRef.current = setInterval(() => {
          setCurrentFrame(prev => {
            const next = prev + 1;

            if (next >= frameCount) {
              if (shouldLoop) {
                // 循环模式：回到第一帧
                updateFrame(0);
                return 0;
              } else {
                // 非循环模式：停在最后一帧
                setIsPlaying(false);
                onPlayEnd?.();
                return prev;
              }
            }

            updateFrame(next);
            return next;
          });
        }, duration);

        return () => {
          clearTimers();
        };
      } else {
        // ========== 选项B: requestAnimationFrame 模式 ==========
        // 优点：更精确，与渲染同步
        // 适用：快速动画，需要高精度的场景

        startTimeRef.current = Date.now();
        lastFrameIndexRef.current = 0;
        console.log('startTime', startTimeRef.current, 'lastFrameIndex', lastFrameIndexRef.current);
        console.log('isPlaying', isPlaying, 'frameCount', frameCount, 'duration', duration);

        const animate = () => {
          const elapsed = Date.now() - startTimeRef.current;
          const calculatedFrame = Math.floor(elapsed / duration);
          console.log('calculatedFrame', calculatedFrame, 'lastFrameIndex', lastFrameIndexRef.current);

          // 只在帧真正变化时更新
          if (calculatedFrame !== lastFrameIndexRef.current) {
            const actualFrame = calculatedFrame % frameCount;
            console.log(
              'actualFrame',
              actualFrame,
              'frameCount',
              frameCount,
              'calculatedFrame >= frameCount',
              calculatedFrame >= frameCount,
              'shouldLoop',
              shouldLoop,
            );

            // 检查是否应该停止（非循环模式）
            if (!shouldLoop && calculatedFrame >= frameCount) {
              updateFrame(frameCount - 1);
              setIsPlaying(false);
              onPlayEnd?.();
              return;
            }

            lastFrameIndexRef.current = calculatedFrame;
            updateFrame(actualFrame);
          }

          rafRef.current = requestAnimationFrame(animate);
        };

        rafRef.current = requestAnimationFrame(animate);

        return () => {
          clearTimers();
        };
      }
    }, [
      isPlaying,
      frameCount,
      duration,
      shouldLoop,
      timingMode,
      updateFrame,
      clearTimers,
      onPlayEnd,
      onPlayStart,
      onPause,
    ]);

    // ==================== 命令式 API ====================

    useImperativeHandle(
      ref,
      () => ({
        // 播放控制
        play: () => setIsPlaying(true),

        pause: () => setIsPlaying(false),

        stop: () => {
          setIsPlaying(false);
          updateFrame(initialFrame);
        },

        toggle: () => setIsPlaying(prev => !prev),

        // 帧控制
        goToFrame: (frameIndex: number) => {
          if (frameIndex >= 0 && frameIndex < frameCount) {
            updateFrame(frameIndex);
          } else {
            console.warn(
              `FrameAnimationController: Invalid frame index ${frameIndex}. Must be between 0 and ${frameCount - 1}.`,
            );
          }
        },

        nextFrame: () => {
          const next = (currentFrame + 1) % frameCount;
          updateFrame(next);
        },

        prevFrame: () => {
          const prev = (currentFrame - 1 + frameCount) % frameCount;
          updateFrame(prev);
        },

        // 状态查询
        getCurrentFrame: () => currentFrame,

        isPlaying: () => isPlaying,

        // 动态配置
        setFrameDuration: (newDuration: number) => {
          if (newDuration > 0) {
            setDuration(newDuration);
          } else {
            console.warn(`FrameAnimationController: Invalid duration ${newDuration}. Must be greater than 0.`);
          }
        },

        setLoop: (newLoop: boolean) => setShouldLoop(newLoop),
      }),
      [currentFrame, isPlaying, frameCount, initialFrame, updateFrame],
    );

    // ==================== 渲染 ====================

    return <>{children(currentFrame)}</>;
  },
);

FrameAnimationController.displayName = 'FrameAnimationController';
